import ipaddress
from re import T
import socket as sock
import struct
import json
buff_size=1024

class client:
    def __init__(self,socket:sock.socket) -> None:
        print('client initing...')
        self.socket=socket
        self.isconnected=True

    def connect(self,ip_address,port):
        print(f'connecting to server {ip_address} on port {port}...')
        self.socket.connect((ip_address,port))
        self.socket.setblocking(False)
        self.isconnected=True

    def request_for_file(self):
        self.socket.send('getfile'.encode())
        file_list=self.recv(buff_size)
        print(file_list)
        file=input("input which file you want:")
        self.socket.send(file.encode())
            # 第一步：先收取报头的长度
        obj = self.recv(4) 
        header_size = struct.unpack('i', obj)[0]

        # 第二步：再收报头
        header_bytes = self.recv(header_size)

        # 第三步：从报头中间解析出对真是数据的描述信息
        header_json = header_bytes.decode('utf-8')
        header_dic = json.loads(header_json)
        print(header_dic)
        total_size = header_dic['file_size']
        filename = header_dic['filename']
        download_dir='c_file'
        with open('%s/%s' % (download_dir, filename), 'wb') as f: # 在自己的电脑中找一个地址打开一个同类型的文件准备接收数据
            recv_size = 0
            while recv_size < total_size:
                line = self.recv(1024)
                f.write(line)
                recv_size += len(line)
                print('总大小：%s   已下载大小：%s' % (total_size, recv_size))
    
    def recv(self,buff_size):
        while True:
            try:
                buff=self.socket.recv(buff_size)
                return buff
            except(BlockingIOError, ConnectionResetError):
                pass
def run():
    socket=sock.socket(sock.AF_INET, sock.SOCK_STREAM)
    c=client(socket) 
    c.connect('127.0.0.1',4444)
    c.request_for_file()
    c.socket.close()

if __name__=='__main__':
    run()